package com.wsz.departments.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsz.departments.feign.EmployeeClient;
import com.wsz.departments.service.DepartmentService;
import com.wsz.pojo.Department;
import com.wsz.pojo.Employee;
import com.wsz.pojo.R;
import com.wsz.pojo.vo.EmployeesVo;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@AllArgsConstructor
@RestController
@RequestMapping("/departments")
public class DepartmentsController {

    private final DepartmentService departmentService;

    private final EmployeeClient employeeClient;

    @GetMapping("/test")
    public String Hello(){
        return "hello dep";
    }

    @GetMapping("/{did}/emos/{eid}")
    public R getEmployeeInfo(@PathVariable Integer did,
                             @PathVariable Integer eid){
        //1.微服务调员工的GetEmployee
        R employee = employeeClient.getEmployee(eid);
        if(employee.getCode().equals(201)){
            return R.error().message("不存在该员工");
        }
        Map<String, Object> data = employee.getData();
        Object tmp = data.get("employee");

        String s = JSON.toJSONString(tmp);
        Employee emp = JSON.parseObject(s, Employee.class);

        BeanUtils.copyProperties(tmp,emp);
        System.out.println(emp);

        EmployeesVo employeesVo = new EmployeesVo();

        BeanUtils.copyProperties(emp,employeesVo);

        Department dep = departmentService.getById(did);

        employeesVo.setDepartment(dep);

        return R.ok().data("employeeInfo",employeesVo);
    }

    @PutMapping("/")
    public R updateDepartment(@RequestBody Department department){
        boolean b = departmentService.updateById(department);
        if(b) return R.ok();
        return R.error().message("更新失败");
    }

    @PostMapping("/")
    public R saveDepartment(@RequestBody Department department){
        boolean save = departmentService.save(department);
        if(save) return R.ok();
        return R.error().message("添加失败");
    }

    @GetMapping("/")
    public R getDepartments(){
        List<Department> list = departmentService.list();
        return R.ok().data("departments",list);
    }

    @GetMapping("/getdeps")
    public R getDepartments(@RequestParam String jsonStr){

        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        JSONArray listJson = jsonObject.getJSONArray("list");//转成数组
        List<Integer> dids = listJson.toJavaList(Integer.class);//转成数组对象
        List<Department> deps = departmentService.list(new QueryWrapper<Department>().in("id", dids));
        return R.ok().data("deps",deps);
    }
}
